package com.fengye.middleware.rabbitmq.boot.ack.auto;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 *
 * @author sky
 * @date 2021年06月09日 2:21 下午
 */
@Component
@Slf4j
public class KnowledgeAutoConfig {
    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;

    @Autowired
    private SimpleRabbitListenerContainerFactoryConfigurer factoryConfigurer;

    @Bean(name = "singleListenerContainerAuto")
    public SimpleRabbitListenerContainerFactory listenerContainerAuto() {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(cachingConnectionFactory);
        // 设置消息在传输中的格式，在这里采用 JSON 格式进行传输
        factory.setMessageConverter(new Jackson2JsonMessageConverter());

        // 设置并发消费者示例的初始数量
        factory.setConcurrentConsumers(1);

        // 设置并发消费者示例的最大数量
        factory.setMaxConcurrentConsumers(1);

        // 设置并发消费者示例中每个示例拉取的数量
        factory.setPrefetchCount(1);
        
        factory.setAcknowledgeMode(AcknowledgeMode.AUTO);
        
        return factory;
    }


    @Value("${mq.knowledge.auto.queue.name:auto_queue_name}")
    private String autoQueueName;

    @Value("${mq.knowledge.auto.exchange.name:auto_change_name}")
    private String autoExchangeName;

    @Value("${mq.knowledge.auto.routing.key.name:auto_routing_key_name}")
    private String autoRoutingKeyName;

    /* 创建简单消息模型：队列、交换机和路由 */

    // 队列
    @Bean(name = "autoQueue")
    public Queue autoQueue(){
        return new Queue(autoQueueName);
    }

    @Bean(name = "autoExchange")
    public DirectExchange autoExchange(){
        return new DirectExchange(autoExchangeName, true, false);
    }

    @Bean
    public Binding autoBinding(Queue autoQueue, DirectExchange autoExchange){
        return BindingBuilder.bind(autoQueue).to(autoExchange).with(autoRoutingKeyName);
    }
    
}
